/**
 * @author GodSon
 * http://www.btboys.com
 * date 2011-4-17 21:30
 */
RIA.nameSpace("os",function(){
    var obj = this;
    this.time = InitTime;
    this.appReset = AppReset;
    this.LogOut = LogOut;
    this.ChangeToolbarWinList = ChangeToolbarWinList;
    this.OSInit = OSInit;
    this.Login = Login;
    /**
     *时间
     */
    function InitTime(){
        var MyDate=new Date();
        var Text=MyDate.getMonth()+"月"+MyDate.getDate()+"日 "+MyDate.toLocaleTimeString()
        $('#GodSon_os_Calendar').text(Text);
    }
    /**
     *初始化APP
     */
    function InitApp(AppList){
        var ListNum=Math.floor((document.body.clientHeight-50)/90);
        var iNum=1,iList=1;
        for(var i=0;i<AppList.length;i++){
            if(iNum>ListNum){
                iNum=1;
                iList++
            }
            var T=10+90*(iNum-1);
            var L=85*iList-80;
            iNum++;
            var appId="App_"+AppList[i].id;
            var appIcon = "app-"+AppList[i].iconCls;
            var app = $("<div id='"+appId+"' style=\"top:"+T+"px;left:"+L+"px\" class='app'><div class='appIcon "+appIcon+"'></div><div class='appText'>"+AppList[i].text+"</div></div>");
            app.data("app",AppList[i]);
            bingAppEvent(app);
            $('.GD_windBody').append(app);
        }
        var f = $('<div style="float:right;"><object id="item_47960" data="sources/widget/clock1.swf" width="110" height="110" type="application/x-shockwave-flash"><param name="allowScriptAccess" value="always"><param name="allownetworking" value="all"><param name="allowFullScreen" value="true"><param name="wmode" value="transparent"><param name="scale" value="noScale"><param name="menu" value="false"></object></div>')
        f.draggable();
        $('.GD_windBody').append(f);
        InitAppDrag();
	
        /**
	 *app的事件绑定
	 **/
        function bingAppEvent(app){
            app.dblclick(AppClik).hover(function(){
                $(this).addClass("IcoOn");
            },function(){
                $(this).removeClass("IcoOn");
            }).mousedown(function(){
                $('.app').removeClass("IcoDown");
                $(this).addClass("IcoDown");
            }).bind('contextmenu',function(e){
                $('#appContextmenu').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
                return false;
            });
        }
    }
    
    /**
     * 初始化图标拖拽
     */
    function InitAppDrag(){
        $('.app').draggable({
            revert:true
        }).droppable({
            onDrop:function(e,source){
                $.data(source, 'draggable').options.revert = true;
                if($(source).prev().attr('id') == $(this).attr('id')){
                    $(source).insertBefore(this);
                }else{
                    $(source).insertAfter(this);
                }
                AppReset();
            },
            onDragOver:function(e,source){
                $.data(source, 'draggable').options.revert = false;
            },
            onDragLeave:function(e,source){
                $.data(source, 'draggable').options.revert = true;
            },
            accept:'.app'
        });
    }
    /**
     *初始化开始菜单
     **/
    function InitStartMenu(Menus){
        Menus = Menus || [];
        var startMenu =$('<div id="startMenu" style="width:200px;"></div>').appendTo('body');
        for(var i=0;i<Menus.length;i++){
            if(Menus[i].children){
                startMenu.append(appendChild(Menus[i].text,Menus[i].children));
            }else{
                var item = $('<div></div>').html(Menus[i].text).attr("url",Menus[i].href).click(AppClik).data("app",Menus[i]);
                startMenu.append(item);
            }
        }
        startMenu.menu();
        startMenu.menu("appendItem",{
            id:"GodSon_os_logout",
            text:"退出"
        });
        $("#GodSon_os_logout").click(LogOut);
        
        function appendChild(itemText,childrens){
            var item = $('<div></div>').append($('<span></span>').html(itemText));
            var ci = $('<div style="width:200px;"></div>');
		
            for(var i=0;i<childrens.length;i++){				
                if(childrens[i].children){
                    item.append(ci.append(appendChild(childrens[i].text,childrens[i].children)));
                }else{
                    item.append(ci.append($('<div></div>').html(childrens[i].text).attr("url",childrens[i].href).click(AppClik).data("app",Menus[i])));
                }
            }
            return item;
        }
	
        $("#KsMenu").click(function(){
            $('#startMenu').menu('show',{
                left:0,
                top:$('.GD_windBody').height()-$('#startMenu').height()-6
            });
        });
    }
    
    function AppReset(){
        var W=document.body.clientWidth-200;
        $("#GD_WinFinfo").css("width",W);
	
        var apps = $(".GD_windBody > div.app");
        var ListNum=Math.floor((document.body.clientHeight-50)/90);
        var iNum=1,iList=1;
        for(var i=0;i<apps.length;i++){
            if(iNum>ListNum){
                iNum=1;
                iList++
            }
            var T=10+90*(iNum-1);
            var L=85*iList-80;
            iNum++;
            $('.GD_windBody').append($(apps[i]).css({
                top:T,
                left:L
            }));
        }
        $('.app').removeClass("IcoOn");
        $('.app').removeClass("IcoDown");
    }
    
    function Login(){
        var loginConfig = {
            url:"index.php/OSLogin",
            title:"登陆",
            height:250,
            width:400,
            resizable:false,
            maximizable:false,
            minimizable:false,
            cache:false,
            draggable:false,
            closable:false,
            shadow:false,
            buttons:[{
                id:"longin_submit",
                text:"登陆",
                handler:function(){
                    LoginSubmit(GETWIN($(this)));
                }
            },{
                text:"注册",
                handler:Register
            }],
            onComplete:function(winId){
                $("#OSLoginForm input").bind('keydown', 'return',function (){
                    LoginSubmit(GETWIN(winId));
                    return false;
                }).eq(0).focus();
            }
        };
        RIA.window(loginConfig);
    }
    
    function LoginSubmit(win){
        if($('#OSLoginForm').form('validate')){
            //获取表单数据
            var params = $('#OSLoginForm').formJsonSerialize();
            $.ajax({
                url:"index.php/OSLogin/login",
                data:params,
                type:"POST",
                async:false,
                success:function(msg){
                    if($.trim(msg) != "success"){
                        RIA.util.cookie.set("osSinaapp","success");
                        OSInit();
                        $(win).destroy();
                    }else{
                        $.messager.alert("提示","登陆失败！账号密码不匹配！");
                    } 
                }
            });
        }
    }
    
    function LogOut(){
        RIA.util.cookie.del("osSinaapp");
        Login ();
        $('.GD_windBody').empty();
        $('#GD_WinList').empty().css("width",0);
    }
    
    function Register(){
        var registerConfig = {
            url:"index.php/OSregister",
            title:"注册",
            height:320,
            width:450,
            resizable:false,
            maximizable:false,
            minimizable:false,
            cache:false,
            draggable:false,
            shadow:false,
            modal:false,
            buttons:[{
                id:"registerBtn",	
                text:"注册",
                handler:function(){
                    RegisterSubmit(GETWIN(this));
                }
            }],
            onComplete:function(){
                $('input[name="username"]').blur(function(){
                    if($.trim($(this).val()) != ""){
                        $.ajax({
                            url:'index.php/OSregister/checkNameUni',
                            data:'username='+$(this).val(),
                            type:'POST',
                            async:false,
                            success:function(data){
                                if(data != "true"){
                                    $.messager.alert("提示","该用户名已经存在！");
                                    $("#registerBtn").linkbutton("disable");
                                }else{
                                    $("#registerBtn").linkbutton("enable");
                                }
                            }
                        });
                    }
                });
            }
        };
        RIA.window(registerConfig);
    }
    
    function RegisterSubmit(win){
        if($('#OSRegisterForm').form('validate')){
            //获取表单数据
            var params = $('#OSRegisterForm').formJsonSerialize();
            $.ajax({
                url:"index.php/OSregister/register",
                data:params,
                type:"POST",
                success:function(msg){
                    if($.trim(msg) == "success"){
                        $("#OS_loginName").val(params['username']);
                        $("#OS_loginPassword").val(params['password']);
                        $(win).destroy();
                    }else{
                        $.messager.alert("提示","注册失败！");
                    } 
                }
            });
        }
    }
    
    function SetCalendarPos(){
        var T = document.body.clientHeight-210;
        var L = document.body.clientWidth-180;
        $('#OS_calendar').css({
            "top":T,
            "left":L,
            "position":"absolute"
        });
    }
    $(window).bind('resize',SetCalendarPos);
    
    function ShowCalendar(){
         SetCalendarPos();
         $('#OS_calendar').slideToggle("normal");
    }
    
    function ChangeToolbarWinList(Ctype){
        if(Ctype==""){
            var N=$("#GD_WinList").children().length;
            $("#GD_WinList").css("width",101*N);
            $("#GD_WinFinfo").scrollLeft($("#GD_WinFinfo")[0].scrollWidth);
            if($("#GD_WinFinfo")[0].clientWidth<$("#GD_WinFinfo")[0].scrollWidth){
                $("#GD_FScro").show()
            }else{
                $("#GD_FScro").hide()
            }
        }
        if(Ctype=="left"){
            $("#GD_WinFinfo")[0].scrollLeft=$("#GD_WinFinfo")[0].scrollLeft-5;
            CWlistTimer=window.setTimeout("Godson.os.os.ChangeToolbarWinList('left')",10);
        }
        if(Ctype=="right"){
            $("#GD_WinFinfo")[0].scrollLeft=$("#GD_WinFinfo")[0].scrollLeft+5;
            CWlistTimer=window.setTimeout("Godson.os.os.ChangeToolbarWinList('right')",10)
        }
        if(Ctype=="out"){
            clearTimeout(CWlistTimer)
        }
    }
    
    function AppClik(){
        $(this).openApp();
        ChangeToolbarWinList("");
    }
    
    function AppRightmenuOpen(){
        $('.GD_windBody > div.IcoDown').openApp();
        ChangeToolbarWinList("");
    }
    
    function DeskAttr(){
        
    }
    
    function AppAttr(){
        
    }
    
    function OSInit(){
        var AppList = [{
            id:'1',
            text:'我的OS',
            iconCls:'system',
            href:'http://www.btboys.com'
        },{
            id:'11',
            text:'个人设置',
            iconCls:'person'
        },{
            id:'12',
            text:'系统配置',
            iconCls:'system-set'
        },{
            id:'7',
            text:'使用反馈',
            iconCls:'message',
            href:'index.php/FeedBack'
        }];
	
        var startMenu = [{
            id:"startMenu1",
            text:"Google",
            href:"http://www.google.com.hk"
        },{
            id:"startMenu2",
            text:"Sina",
            href:"http://www.sina.com"
        },

        {
            id:"startMenu3",
            text:"GodSon",
            href:"http://www.btboys.com"
        }];

        $('.GD_windBody').bind('contextmenu',function(e){
            $('#deskTopContextmenu').menu('show', {
                left: e.pageX,
                top: e.pageY
            });
            return false;
        });
        var W=document.body.clientWidth-200;
        $("#GD_WinFinfo").css("width",W);
        $(window).bind('resize',AppReset);

        InitApp(AppList);
        InitStartMenu(startMenu);
        setInterval(obj.time,1000);
        
        $("#GodSon_os_ref").bind("click",AppReset);
        $("#GodSon_os_deskAttr").bind("click",DeskAttr);
        $("#GodSon_os_appOpen").bind("click",AppRightmenuOpen);
        $("#GodSon_os_appAttr").bind("click",AppAttr);
        $("#GodSon_os_Calendar").bind("click", ShowCalendar);
    }
    
});